package goutil
import (
	"os"
	"path/filepath"
	"strings"
)

// 判断所给路径文件/文件夹是否存在
func Exists(path string) bool {
	_, err := os.Stat(path) //os.Stat获取文件信息
	if err != nil {
		return os.IsExist(err)
	}
	return true
}
func IsFile(path string) bool {
	f, err := os.Stat(path) //os.Stat获取文件信息
	if err != nil {
		return os.IsExist(err)
	}
	return !f.IsDir()
}
func IsDir(path string) bool {
	f, err := os.Stat(path) //os.Stat获取文件信息
	if err != nil {
		return os.IsExist(err)
	}
	return f.IsDir()
}

type Dir struct {
	Path  string
	Files []string
	Names []string
	Exts  []string
	Dirs  []string
}

func NewDir(path string) *Dir {
	d := &Dir{}
	if Exists(path) {
		d.Path = path
		files, _ := os.ReadDir(path)
		for _, v := range files {
			abs := filepath.Join(path, v.Name())
			if v.IsDir() {
				d.Dirs = append(d.Dirs, abs)
			} else {
				d.Files = append(d.Files, abs)
				ext := filepath.Ext(v.Name())
				d.Names = append(d.Names,
					strings.TrimSuffix(v.Name(), ext))
				d.Exts = append(d.Exts, ext)
			}
		}
	}
	return d
}
func (d *Dir) Do(fn func()) *Dir {
	if fn != nil {
		fn()
	}
	return d
}
func (d *Dir) IterFiles(fn func(s string)) *Dir {
	if fn != nil && len(d.Names)>0{
		for _, v := range d.Names {
			fn(v)
		}
	}
	return d
}
func (d *Dir) IterDirs(fn func(s string)) *Dir {
	if fn != nil && len(d.Dirs)>0{
		for _, v := range d.Dirs {
			fn(v)
		}
	}
	return d
}